package com.dolphin.aiagentplatform.interceptor;

import com.dolphin.aiagentplatform.constant.ResponseCodeConst;
import com.dolphin.aiagentplatform.exception.BusinessException;
import com.dolphin.aiagentplatform.model.vo.user.UserVO;
import com.dolphin.aiagentplatform.utils.TokenManager;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * JWT拦截器
 * 用于验证请求中的JWT令牌
 */
@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Resource
    private TokenManager tokenManager;

    @Override
    public boolean preHandle(
            HttpServletRequest request,
            HttpServletResponse response,
            Object handler) {
        // 获取请求URI
        String uri = request.getRequestURI();
        log.debug("JwtInterceptor preHandle, uri: {}", uri);

        // 放行登录、注册等不需要验证的接口
        if (isPublicUri(uri)) {
            log.debug("公开接口，无需认证: {}", uri);
            return true;
        }

        // 从请求中获取令牌
        String token = tokenManager.getTokenFromRequest(request);
        log.debug("从请求获取令牌: {}", token);

        // 验证token
        UserVO userVO = tokenManager.getLoginUser(request);
        if (userVO == null) {
            // 用户未登录或token无效
            log.warn("用户未登录或token无效，拒绝访问: {}", uri);
            throw new BusinessException(ResponseCodeConst.NOT_LOGIN_ERROR, "用户未登录或登录已过期");
        }
        
        log.debug("用户认证成功: {}，权限: {}", userVO.getUsername(), userVO.getRole());

        // 刷新token有效期
        tokenManager.refreshUserToken(request);
        return true;
    }

    /**
     * 判断是否为公开接口
     */
    private boolean isPublicUri(String uri) {
        // 登录注册接口
        if (uri.contains("/user/login") || uri.contains("/user/register")) {
            return true;
        }

        // 静态资源和Swagger文档
        if (uri.contains("/static/") || uri.contains("/doc.html") || uri.contains("/swagger")
                || uri.contains("/v3/api-docs") || uri.contains("/webjars") || uri.contains("/favicon.ico")) {
            return true;
        }

        // 健康检查
        if (uri.contains("/actuator/")) {
            return true;
        }

        return false;
    }
} 